<template>
  <div>
    <el-form class="lable-top" label-position="top" size="mini">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="search.start_time"
              :picker-options="pickerOptions"
              placeholder="选择日期时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="search.end_time"
              :picker-options="pickerOptions"
              placeholder="选择日期时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item v-permission="['super']" label="组织">
            <el-select v-model="search.org_id" filterable>
              <el-option
                v-for="(item, index) in company"
                :key="index"
                :label="item.name"
                popper-class="w100"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label=" ">
            <el-button @click="handleClick">查询狩猎日志</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button size="small" @click="down">下载日志</el-button>
    <el-table
      class="mt10"
      :data="tableData"
      :header-cell-style="{ background: '#f5f5f5' }"
      size="mini"
    >
      <el-table-column label="用户 ID" prop="user_id" sortable />
      <el-table-column label="用户邮箱" prop="email" sortable />
      <el-table-column label="IP" prop="ip" sortable />
      <el-table-column label="请求时间" prop="time" sortable />
      <el-table-column label="MEQL" prop="query" sortable />
      <el-table-column label="目标组织 ID" prop="org_id" sortable />
      <el-table-column label="目标终端 ID" prop="agent_id" sortable />
      <el-table-column label="开始时间" prop="start_time" sortable />
      <el-table-column label="结束时间" prop="end_time" sortable />
    </el-table>
    <div class="mt10 el-row--flex is-justify-end">
      <el-pagination
        background
        :current-page="page"
        layout="total, prev, pager, next"
        :page-size="limit"
        :page-sizes="[100, 200, 300, 400]"
        small
        :total="count"
        @current-change="handleCurrentChangePage"
      />
    </div>
  </div>
</template>

<script>
import org_getall from "@/utils/mixin/org_getall";
import audit from "@/api/audit";
export default {
  name: "HunterLog",
  mixins: [org_getall],
  data: () => {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "7 天前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          },
          {
            text: "30 天前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            }
          },
          {
            text: "90 天前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      tableData: [],
      search: {
        org_id: "",
        start_time: "",
        end_time: ""
      },
      limit: 50,
      page: 1,
      count: 0
    };
  },
  mounted() {
    this.loadingData();
  },
  methods: {
    saveCsv(data) {
      let filename = new Date().getTime().toString() + ".csv";
      if (!data.length) {
        return;
      }

      if (typeof data === "object") {
        data = JSON.stringify(data, undefined, 4);
      }
      var blob = new Blob([data], { type: "text/json" });
      var e = document.createEvent("MouseEvents");
      var a = document.createElement("a");
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
      e.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      a.dispatchEvent(e);
    },
    down() {
      let data = this.tableData.slice(0);
      let str = data
        .map(k => {
          delete k.time;
          return Object.keys(k)
            .map(e => k[e])
            .join(",");
        })
        .join("\n");
      this.saveCsv(str);
    },
    async loadingData() {
      await this.loadingOrgGetall();
      await this.loadingLog();
    },
    loadingLog() {
      let data = Object.assign({}, this.search);
      data.start_time = data.start_time || "2000-01-01 08:00:00";
      data.end_time = data.end_time || new Date().Format("yyyy-MM-dd hh:mm:ss");
      return audit
        .hunter({
          limit: this.limit,
          page: this.page,
          ...data
        })
        .then(res => {
          this.count = res.data.count;
          this.tableData = res.data.record.map(k => {
            k.time = new Date(k.timestamp).Format("yyyy-MM-dd hh:mm:ss");
            k.start_time = new Date(k.start_time).Format("yyyy-MM-dd hh:mm:ss");
            k.end_time = new Date(k.end_time).Format("yyyy-MM-dd hh:mm:ss");
            return k;
          });
        });
    },
    handleClick() {
      this.page = 1;
      this.loadingLog();
    },
    handleCurrentChangePage(val) {
      this.page = val;
      this.loadingLog();
    }
  }
};
</script>

<style scoped></style>
